<template>
  <div>
    <el-card>
      <classFilter @appointInvitationFunc="appointInvitationFunc" @screenFunc="screenFunc" @searchFunc="searchFunc"
        @showLoginBox="dialogVisible = true" @showActivetBox="init" @recoyerOyeryuer="reloadConetr" />
      <intelligentTable @showDrawerFunc="showDrawerFunc" :params="params" :searchVal="searchVal"
        @showLoginBox="dialogVisible = true" @showActivetBox="init" v-if="params" ref="recoyerOyerOnger" />
      <batchInvitation v-if="isDrawer" :isDrawer.sync="isDrawer" :tableData="tableData" />
    </el-card>
    <el-backtop :visibility-height="100"></el-backtop>
    <LoginBoxContent :dialogVisible="dialogVisible" @closeDialog="dialogVisible = false" @init="init" />
    <ActivetBoxContent :dialogVisible="dialogVisibleActivet" @closeDialog="dialogVisibleActivet = false" />
    <div class="erweima">
      <img src="https://wtplugwt.oss-cn-hangzhou.aliyuncs.com/webimages/code/wkyy/2731728695543_.pic.jpg"
        class="imgaecone" alt="">
    </div>
  </div>
</template>

<script>
import classFilter from "./components/class-filter.vue";
import intelligentTable from "./components/intelligent-table.vue";
import batchInvitation from "./components/batchInvitation/batchInvitation.vue";
import crossClass from "@/utils/cross-domain.js";
import { tips } from "@/api/invitation";
import { activeInfo, activeShop } from "@/api/yywkapi";
import LoginBoxContent from "@/components/userRefoBox/login.vue";
import ActivetBoxContent from "@/components/userRefoBox/activetiBox.vue";
import { index, shopLogin, index_data } from "@/api/shopsApi";
export default {
  components: {
    classFilter,
    intelligentTable,
    batchInvitation,
    LoginBoxContent,
    ActivetBoxContent,
  },
  created() {
    this.init();
  },
  data() {
    return {
      params: null,
      searchVal: "",
      isDrawer: false,
      tableData: null,
      dialogVisible: false,
      dialogVisibleActivet: false,
    };
  },
  mounted() {
    this.initSet();
  },
  methods: {
    reloadConetr() {
      console.log("掉用重置");
      this.$refs.recoyerOyerOnger.recoyerOyer();
    },
    init() {
      console.log("进入邀约");
      if (!this.$store.state.yywk.yywktoken) {
        this.dialogVisible = true;
        return;
      }
      // 获取激活信息
      activeInfo({
        token: this.$store.state.yywk.yywktoken,
      }).then((res) => {
        console.log("rererer", res);

        this.$store.commit("yywk/SET_ACTIVETSTATUS", res.data);
        if (res.code == 0) {
          if (!res.data.activeAt || !res.data.activeEnd) {
            console.log("弹出激活的窗口");
            this.dialogVisibleActivet = true;
            return;
          }
          if (new Date().getTime() > new Date(res.data.activeEnd).getTime()) {
            this.dialogVisibleActivet = true;
            return;
          }

          this.getShopInfo(res.data);
          return;
        }
        if (res.code == 422) {
          this.dialogVisible = true;
          this.$store.dispatch("yywk/setLoginUserInfos", {
            yywktoken: "",
            yywkusername: "",
            yywklastLogin: "",
          });
        }
      });
    },
    async getShopInfo(data) {
      const WT_requestcp = window.WT_request_wk;
      if (WT_requestcp) {
        index()
          .then((res) => {
            if (res.code === 0) {
              const { id, shop_name } = res.data;
              // 判断是否已经使用完所有的激活
              //   activeNum >= availableNum + activeNum
              // console.log(
              //   'data.activeNum >= data.availableNum + data.activeNum',
              //   data.activeNum >= data.availableNum + data.activeNum
              // )


              const findShelId = data.activeList.find((item) => item[0] == id);
              // data.activeList.includes(id)
              if (!findShelId) {
                if (data.activeNum >= data.availableNum + data.activeNum) {
                  this.$confirm(
                    `当前激活码已激活${data.activeNum
                    }个店铺,单个激活码最多可激活${data.availableNum + data.activeNum
                    }个,请添加激活码后绑定店铺使用`,
                    "提示",
                    {
                      confirmButtonText: "前往激活",
                      cancelButtonText: "取消",
                      type: "warning",
                    }
                  ).then(() => {
                    this.dialogVisibleActivet = true;
                  });
                  return;
                }
                this.$confirm(
                  `是否使用当前账号激活当前店铺${shop_name}`,
                  "提示",
                  {
                    confirmButtonText: "当前账号",
                    cancelButtonText: "切换账号",
                    type: "warning",
                    closeOnClickModal: false,
                    distinguishCancelAndClose: true,
                  }
                )
                  .then(() => {
                    // this.dialogVisibleActivet = true
                    activeShop({
                      token: this.$store.state.yywk.yywktoken,
                      shopId: id,
                    })
                      .then((res) => {
                        if (res.code == 0) {
                          this.$message({
                            message: "店铺激活成功",
                            type: "success",
                          });
                          this.$store.commit(
                            "yywk/SET_ACTIVETSTATUS",
                            res.data
                          );
                          //   this.getShopInfo(res.data)
                        } else {
                          this.$message({
                            message: res.msg,
                            type: "error",
                          });
                        }
                      })
                      .catch((err) => {
                        this.$message.error("店铺激活失败");
                      });
                  })
                  .catch((e) => {
                    // console.log('eee', eee)
                    if (e === "cancel") {
                      this.$store.dispatch("yywk/setLoginUserInfos", {
                        yywktoken: "",
                        yywkusername: "",
                        yywklastLogin: "",
                      });
                      window.location.reload();
                    }
                  });
                return;
              }
              console.log('可以用')
              //   if(new Date( findShelId[1][1]) <= new Date()) {
              //     this.$confirm(
              //       `当前店铺${shop_name}已过期，是否使用当前账号激活当前店铺`,
              //       '提示',
              //       {
              //         confirmButtonText: '当前账号',
              //         cancelButtonText: '切换账号',
              //         type: 'warning',
              //       }
              //     )

              //   }
              // console.log('般的', data, res)
            }
          })
          .catch((error) => {
            // console.log('errorerrorerrorerror', error)
            this.$message.error("使用该功能，需要打开并登录抖店。");
          });
      }
      return true;
    },
    async initSet() {
      const that = this;
      const TipsFunc = (str, url) => {
        this.$confirm(str, "提示", {
          confirmButtonText: "前往打开",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            window.open(url);
          })
          .catch((err) => { })
          .finally(() => {
            setTimeout(() => {
              that.$router.go(0);
            }, 3000);
          });
      };
      const crossInstance = new crossClass();
      let checkUrlOpen = await crossInstance.checkUrlOpen([
        "https://buyin.jinritemai.com/dashboard", //达人广场
        "https://fxg.jinritemai.com/ffa", // 抖店后台
      ]);
      let { code, data } = checkUrlOpen;
      console.log("checkUrlOpen", checkUrlOpen);
      if (code == 200) {
        let douDian = data.find((item) => {
          // console.log('item', item)
          return (
            item.url == "https://fxg.jinritemai.com/ffa" && item.status == true
          );
        });
        let darenSquare = data.find((item) => {
          return (
            item.url == "https://buyin.jinritemai.com/dashboard" &&
            item.status == true
          );
        });
        if (!douDian) {
          let str = "使用该功能需要打开并登录抖店";
          let url = "https://fxg.jinritemai.com/login/common?from=buyin";
          TipsFunc(str, url);
          crossInstance.closeListen();
          return;
        }
        if (!darenSquare) {
          let str = "使用该功能需要打开并登录达人广场";
          let url =
            "https://buyin.jinritemai.com/login/transfer?app_id=4272&subject_aid=4966&mode=1&login_source=buyin&from_source=doudian_pc_web&redirect_url=%2Fdashboard";
          TipsFunc(str, url);
          crossInstance.closeListen();
          return;
        }

        crossInstance
          .sendMessageForPageFunc({
            id: darenSquare.id,
            script: `fetch('https://buyin.jinritemai.com/trade_online_pc_api/shop/intercept/tips',{
                            method: 'GET',
                            })
                            .then((res) => {
                            return res.json()
                            })
                            .then((res) => {
                            window.postMessage({
                                    type_urs: 'wkyy-wtbg',
                                    data: res,
                                    type_page: 'pageMeat',
                                    method: 'send_message_for_page'
                                })
                            })
                        `,
          })
          .then((res) => {
            // console.log(res, '11111')
            let { code, data } = res;
            if (
              code == 200 &&
              data.code == -1 &&
              data.msg == "您已被关闭推广，无法使用平台功能"
            ) {
              this.$message.error(
                "您暂时还不满足邀约达人的条件，请前往官网开通该权限"
              );
            }
            crossInstance.closeListen();
          })
          .catch((err) => {
            crossInstance.closeListen();
          });
        setTimeout(() => {
          crossInstance.closeListen();
        }, 2000);
      }
    },
    screenFunc(params, val) {
      // console.log('params123456', params, val)
      this.params = JSON.parse(JSON.stringify(params));
      console.log(val);
      this.searchVal = JSON.parse(JSON.stringify(val == undefined ? "" : val));
    },
    searchFunc(val) {
      this.searchVal = JSON.parse(JSON.stringify(val));
    },
    showDrawerFunc(data) {
      // alert(data)
      this.tableData = data;
      this.isDrawer = true;
    },
    // 指定达人邀约
    appointInvitationFunc(val) {
      this.searchVal = JSON.parse(JSON.stringify(val));
      setTimeout(() => {
        let row = this.$refs.recoyerOyerOnger.tableData;
        this.$refs.recoyerOyerOnger.showDrawer([...row], true);
      }, 800);
    },
  },
};
</script>

<style scoped lang="scss">
.erweima {
  position: fixed;
  bottom: 20px;
  left: 20px;
  z-index: 999999999;
  background-color: aquamarine;
  width: 180px;
  height: 240px;

  .imgaecone {
    width: 100%;
    height: 100%;
  }
}
</style>
